<?php
/**[字段表模型]
 * @Author: 976123967@qq.com
 * @Date:   2014-09-23 11:06:13
 * @Last Modified by:   Administrator
 * @Last Modified time: 2014-12-26 11:31:00
 */
class FieldModel extends Model{

	protected $tableName = 'model_field';
	public $field;

	/**
	 * [$_validate 自动验证]
	 * @var array
	 */
	protected $_validate = array(
		array('title','require','请输入字段标题',1,'regex',3),
		array('title','_title','字段标题已经存在',1,'callback',3),
		array('fname','require','请输入字段名',1,'regex',3),
		array('fname','/^[a-z][a-z0-9_]*$/i','字段名必须以字母开头并且只能包含字母或者数字或者下划线',1,'regex',3),
		array('fname','_fname','字段名已经存在',1,'callback',3),
	);
	protected function _title($con)
	{
		$mid = I('post.mid');
		$fid = I('post.fid');
		if($fid)
			$where['fid'] = array('neq',$fid);
		$where['title'] = $con;
		$where['model_mid'] = $mid;
		$sta = $this->where($where)->getField('fid');
		if($sta)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	protected function _fname($con)
	{
		$mid = I('post.mid');
		$fid = I('post.fid');
		if($fid)
			$where['fid'] = array('neq',$fid);
		$where['fname'] = strtolower($con);
		$where['model_mid'] = $mid;
		$sta = $this->where($where)->getField('fid');
		if($sta)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	/**
	 * [$_auto 自动完成]
	 * @var array
	 */
	protected $_auto = array(
		array('model_mid','_mid',3,'callback'),
		array('sort','intval',3,'function'),
		array('fname','strtolower',3,'function'),
	);
	
	protected function _mid()
	{
		return  I('post.mid');

	}

	/**
	 * [_initialize 初始化]
	 * @return [type] [description]
	 */
	public function _initialize()
	{
		$this->field = S('field');
	}

	/**
	 * [update_cache 更新缓存]
	 * @return [type] [description]
	 */
	public function update_cache()
	{
		$data = $this->order('sort asc,fid desc')->select();

		$fieldValueModel = D('FieldValue');
		$temp = array();
		if($data)
		{
			foreach($data as $k=>$v)
			{
				$v['field_value'] = $fieldValueModel->get_field_all($v['fid']);
				$temp[$v['model_mid']][]=$v;
			}
		}

		S('field',$temp);
	}


	/**
	 * [add_model_field 添加字段]
	 * @param [type] $data [description]
	 */
	public function  add_model_field($data)
	{
		$this->add($data);
		$this->update_cache();
	}

	/**
	 * [del_model_field 删除字段信息]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function del_model_field($mid)
	{
		$data = $this->where(array('model_mid'=>$mid))->getField('fid',true);

		$fieldValueModel = D('FieldValue');
		foreach($data as $v)
		{
			$fieldValueModel->delete_value($v);
		}

		$this->where(array('model_mid'=>$mid))->delete();
		$this->update_cache();
	
	}

	/**
	 * [get_field_all 模型中所有字段]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_field_all($mid)
	{
		$field = $this->field[$mid];
	
		// 1 文本 ，2多行文本 ，3 编辑器 4简单编辑器 ，5 单选框 ，6下拉框，7多选框 ，8文件上传框，9图片上传框 ， 10地区联动
		$type = '';
		foreach($field as $k=>$v)
		{
			// 禁用
			$field[$k]['disabled'] = $v['is_disabled']?'关闭':'正常';
			// 系统
			$field[$k]['system'] = $v['is_system']?'系统':'用户';
			$field[$k]['show_lists'] = $v['show_lists']?'显示':'不显示';
			// 类型
			switch ($v['show_type']) {
				case 1:
					$type = '文本';
					break;
				case 2:
					$type = '多行文本';
					break;
				case 3:
					$type = '编辑器';
					break;
				case 4:
					$type = '简单编辑器';
					break;
				case 5:
					$type = '单选框';
					break;
				case 6:
					$type = '下拉框';
					break;
				case 7:
					$type = '多选框';
					break;
				case 8:
					$type = '文件上传框';
					break;
				case 9:
					$type = '图片上传框';
					break;
				case 10:
					$type = '地区联动';
					break;
			}
			$field[$k]['type'] = $type;
		}
		return $field;
	}


	/**
	 * [add_field 添加字段]
	 */
	public function add_field()
	{

		// 更改表结构
		// 数据库字段类型
		$type = $this->get_type(I('post.show_type'));

		$mid = I('post.mid');
		$table = C('DB_PREFIX').'article_'.D('Model')->get_field($mid,'name');
		$fname = I('post.fname');
		$title = I('post.title');

		if($type!='text')
		{
			$type = ' VARCHAR(255) NOT NULL DEFAULT "" ';
			$sql='ALTER TABLE `'.$table.'` ADD  `'.$fname.'` '. $type;
		}
		else
		{
			$type = ' text NOT NULL ';
			$sql='ALTER TABLE `'.$table.'` ADD  `'.$fname.'` '. $type;
		}
		$sql .= "COMMENT '{$title}'";

		//echo $sql;die;

		$this->query($sql);


		
		$fid = $this->add();
		
		$value =  I('post.field_value');

		$fieldValueModel = D('FieldValue');
		foreach($value  as $v)
		{
			$data = array(

				'field_fid'=>$fid,
				'field_value'=>$v,

			);

			$fieldValueModel->add_field_value($data);

		}
		$this->update_cache();
	

	}



	/**
	 * [get_type 更具字段展示类型返回字段类型]
	 * @return [type] [description]
	 */
	public function get_type($showType)
	{	
		// 类型
		switch ($showType) {
			case 1:
				$type = 'varchar';

				break;
			case 2:
				$type = 'varchar';

				break;
			case 3:
				$type = 'text';

				break;
			case 4:
				$type = 'text';
				break;
			case 5:
				$type = 'varchar';
				break;
			case 6:
				$type = 'varchar';
				break;
			case 7:
				$type = 'varchar';
				break;
			case 8:
				$type = 'varchar';
				break;
			case 9:
				$type = 'varchar';
				break;
			case 10:
				$type = 'varchar';
				break;
		}
		return $type;

	}


	/**
	 * [find_one 获取字段单条信息]
	 * @param  [type] $fid [description]
	 * @return [type]      [description]
	 */
	public function find_one($fid)
	{
		return  $this->find($fid);
	}

	public function edit_field()
	{
		
		

		$fid = I('post.fid');



		// 更改表结构
		// 数据库字段类型
		$type = $this->get_type(I('post.show_type'));

		$mid = I('post.mid');
		$table = C('DB_PREFIX').'article_'.D('Model')->get_field($mid,'name');
		$fname = I('post.fname');
		$title = I('post.title');
		
		$oldname = $this->where(array('fid'=>$fid))->getField('fname');
	

		if($type!='text')
		{
			$type = ' VARCHAR(255) NOT NULL DEFAULT "" ';
			$sql='ALTER TABLE `'.$table.'` CHANGE  `'.$oldname.'` '. $fname . $type;
		}
		else
		{
			$type = ' text  ';
			$sql='ALTER TABLE `'.$table.'` CHANGE  `'.$oldname.'` '. $fname . $type;
		}
		$sql .= "COMMENT '{$title}'";
		
		

		$this->query($sql);





		$this->save();
		$value =  I('post.field_value');
		$fieldValueModel = D('FieldValue');
		$fieldValueModel->delete_value($fid);
		foreach($value  as $k=> $v)
		{

			$data = array(

				'field_fid'=>$fid,
				'field_value'=>$v,

			);

			$key = explode('-', $k);
			if(isset($key[0]))
			{
				$data['fv_id']=$key[0];
			}

			$fieldValueModel->add_field_value($data);

		}
		$this->update_cache();

		


	}

	/**
	 * [del_field 删除字段]
	 * @param  [type] $fid [description]
	 * @return [type]      [description]
	 */
	public function del_field($fid)
	{
		// 更改表结构
		$mid = I('get.mid');
		$table = C('DB_PREFIX').'article_'.D('Model')->get_field($mid,'name');
		$fname = $this->where(array('fid'=>$fid))->getField('fname');

		$sql = "ALTER TABLE  `" . $table ."`  DROP  ".$fname;
		$this->query($sql);


		$this->delete($fid);
		D('FieldValue')->delete_value($fid);

		$this->update_cache();
	}




	public function get_field_form($mid,$value=array())
	{
		$fieldAll = $this->field;
		$field = $fieldAll[$mid];
		$model = D('Model')->model[$mid];
		$form  = array();
		//p($field);
		foreach($field as $v)
		{
			if($v['fname']=='article_aid')
				continue;
			if($v['is_disabled'])
				continue;
			switch ($v['show_type']) {
				case 1: //文本框
					$temp = $value[$v['fname']];
					$result = "<input name = '{$v['fname']}' type='text' value='{$temp}' class='hd-w200' />";
					break;
				case 2: //多行文本框
					$temp = $value[$v['fname']];
					$result = "<textarea name = '{$v['fname']}' class='hd-w500 hd-h100'>{$temp}</textarea>";
					break;
				case 3: //完整编辑器
					$temp = $value[$v['fname']];
					$result =  keditor(array('name'=>$v['fname'],'content'=>$temp));
					break;
				case 4: //简单编辑器
					$temp = $value[$v['fname']];
					$result =  keditor(array('name'=>$v['fname'],'content'=>$temp,'style'=>2));
					break;
				case 5: //单选框
					$result ='';
					$temp = $value[$v['fname']];
					foreach($v['field_value'] as $f)
					{	
						$checked = $temp == $f['field_value']?"checked='checked'":"";
						$result .= "<label ><input {$checked} type='radio'  name='{$v[fname]}' value='{$f[field_value]}' /> {$f[field_value]}</label>";
					}
				
					break;
				case 6: //下拉框
					$result = "<select name='{$v["fname"]}'>";
					$temp = $value[$v['fname']];
					foreach($v['field_value'] as $f)
					{	
						$selected = $temp == $f['field_value']?"selected='selected'":"";
						$result .= "<option {$selected} value='{$f[field_value]}'>{$f[field_value]}</option>";
					}
					$result .= "</select>";
					break;
				case 7: //多选框
					$result ='';
					$temp = $value[$v['fname']];
					foreach($v['field_value'] as $f)
					{	
						$checked = strchr($temp,$f['field_value'])?"checked='checked'":"";
						$result .= "<label ><input {$checked} type='checkbox'  name='{$v[fname]}[]' value='{$f[field_value]}' /> {$f[field_value]}</label>";
					}
				
					break;
				case 8: //文件上传
					$temp = $value[$v['fname']];
					$result = "<input name='{$v["fname"]}' type='file'  />";
					if($temp)
					{
						$result .= "<br/> <a href='".U('down',array('aid'=>$value['aid'],'field'=>$v["fname"]))."'>下载</a>";
						$result .= "&nbsp;<a href='javascript:;' onclick='del_attachment(this,{$value[aid]},\"$v[fname]\")'>删除</a>";
						$result .= "<input type='hidden' name='table' value='article_{$model[name]}' />";
					}
					break;
				case 9: //图片上传
					$temp = $value[$v['fname']];
					$result = "<input name='{$v["fname"]}' type='file'  />";
					if($temp)
					{
						$result .= "<br/><img src='".__ROOT__."/".$temp."' width='100' />";
						$result .= "&nbsp;<a href='javascript:;' onclick='del_attachment(this,{$value[aid]},\"$v[fname]\")'>删除</a>";
						$result .= "<input type='hidden' name='table' value='article_{$model[name]}' />";
					}
					break;
				case 10:
					$result = '地区联动';
					break;
			}
			$form[] = array('html'=>$result,'title'=>$v['title']);
			
		}

		
		return $form;
	}


	/**
	 * [get_validate 获取js验证]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_validate($mid)
	{
		$field = $this->field[$mid];

		$valiate = "article_title:{rule:{required:true,},error:{required:'请输入文档标题'},message:'请输入文档标题'},sort:{rule:{required:true,regexp:/^\d+$/},error:{required:'请输入排序值',regexp:'排序值只能是数字'},message:'请输入排序值'},click:{rule:{required:true,regexp:/^\d+$/},error:{required:'请输入点击次数',regexp:'点击次数只能是数字'},message:'请输入点击次数'},";
		foreach($field as $v)
		{
			if($v['fname']=='article_aid' || $v['fname']=='body') continue;
			$valiate .= $v['fname'].":{ rule:{";
		
			// 验证必填
			// 规则
			if($v['require'])
			{
				$valiate .=" required:true,";
			}
			if($v['validate'])
			{
				$valiate .= "regexp:".$v['validate'].",";
			}
			$valiate = rtrim($valiate,',');


			$valiate .="},error:{";

			// 错误提示
			if($v['require'])
			{
				$valiate .= " required: '请输入".$v['title']."',";
			}
			if($v['validate'])
			{
				$valiate .= "regexp:'".$v['error']."',";
			}
			$valiate = rtrim($valiate,',')."}";
		
			if($v['require']&& ($v['show_type'] == '1'|| $v['show_type'] == '2'))
				$valiate .=",message: '请输入".$v['title']."',";
			$valiate .= "},";
		
		}
		$valiate = rtrim($valiate,',');
		return $valiate;
	}


	/**
	 * [get_lists_field 列表显示的字段]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_lists_field($mid)
	{
		$field = $this->field[$mid];
		$result = array();
		if($field)
		{
			foreach($field as $v)
			{
				if($v['show_lists'])
					$result[]=$v['fname'];
			}
		}
		if(!empty($result))
			return implode(',', $result);
		else
			 return false;
	}


	/**
	 * [update_order 排序]
	 * @return [type] [description]
	 */
	public function update_order()
	{
		$fid = I('post.fid');
		if(empty($fid))
		{
			$this->error='没有字段信息用于排序';
			return false;
		}
		$listOrder = I('post.list_order');
		foreach($fid as $k => $v)
		{
			$data = array(
				'sort'=>$listOrder[$k]
			);
			$this->where(array('fid'=>$v))->save($data);
		}

		$this->update_cache();
		return true;
	}

}